/**
 * Notes: 绩效统计管理
 *  
 * Date: 2023-09-01 07:48:00 
 */

const BaseProjectAdminService = require('./base_project_admin_service.js');
const util = require('../../../../framework/utils/util.js');
const exportUtil = require('../../../../framework/utils/export_util.js');
const timeUtil = require('../../../../framework/utils/time_util.js');
const dataUtil = require('../../../../framework/utils/data_util.js');
const PerformanceModel = require('../../model/performance_model.js');
const TaskModel = require('../../model/task_model.js');
const MemberModel = require('../../model/member_model.js');

// 导出数据KEY
const EXPORT_PERFORMANCE_DATA_KEY = 'EXPORT_PERFORMANCE_DATA';

class AdminPerformanceService extends BaseProjectAdminService {

    /**
     * 计算绩效统计
     * @param {*} startDate 开始时间戳
     * @param {*} endDate 结束时间戳
     * @param {*} workPointPerTask 每个任务的工分
     * @param {*} bonusPerPoint 每个工分对应的奖金
     */
    async calcPerformance(startDate, endDate, workPointPerTask, bonusPerPoint, admin) {
        if (startDate >= endDate) this.AppError('开始时间不能大于或等于结束时间');

        // 清理旧数据
        let whereOld = {
            PERFORMANCE_START_DATE: startDate,
            PERFORMANCE_END_DATE: endDate,
        };
        await PerformanceModel.del(whereOld);

        // 获取所有工作人员
        let memberWhere = {
            MEMBER_STATUS: MemberModel.STATUS.COMM
        };
        let memberList = await MemberModel.getAll(memberWhere, 'MEMBER_TITLE,MEMBER_CATE_ID,MEMBER_CATE_NAME');
        
        let performanceList = [];
        
        // 遍历每个工作人员计算绩效
        for (let member of memberList) {
            // 查询该员工在指定时间段内的已完成工单数量
            let whereTask = {
                TASK_MEMBER_ID: member._id,
                TASK_STATUS: TaskModel.STATUS.OVER,
                TASK_OVER_TIME: ['between', startDate, endDate]
            };
            let taskCnt = await TaskModel.count(whereTask);
            
            // 计算工分和绩效奖金
            let workPoints = taskCnt * workPointPerTask;
            let bonus = workPoints * bonusPerPoint;
            
            // 构建绩效记录
            let performance = {
                PERFORMANCE_MEMBER_ID: member._id,
                PERFORMANCE_MEMBER_NAME: member.MEMBER_TITLE,
                PERFORMANCE_MEMBER_CATE_ID: member.MEMBER_CATE_ID,
                PERFORMANCE_MEMBER_CATE_NAME: member.MEMBER_CATE_NAME,
                
                PERFORMANCE_START_DATE: startDate,
                PERFORMANCE_END_DATE: endDate,
                
                PERFORMANCE_TASK_CNT: taskCnt,
                PERFORMANCE_WORK_POINTS: workPoints,
                PERFORMANCE_BONUS: bonus,
                
                PERFORMANCE_SCORE: 0, // 默认评分0，等待所长/班长评分
                PERFORMANCE_REMARK: '',
                
                PERFORMANCE_LEADER_ID: admin._id,
                PERFORMANCE_LEADER_NAME: admin.ADMIN_NAME
            };
            
            // 添加到性能列表
            performanceList.push(performance);
        }
        
        // 批量添加性能记录
        await PerformanceModel.insertBatch(performanceList);
        
        return {
            count: performanceList.length,
            startTime: timeUtil.timestamp2Time(startDate),
            endTime: timeUtil.timestamp2Time(endDate)
        };
    }

    /**
     * 修改绩效评分和评价
     */
    async editPerformanceScore(id, score, remark, admin) {
        if (score < 0 || score > 10) this.AppError('评分需在0-10分之间');
        
        let data = {
            PERFORMANCE_SCORE: score,
            PERFORMANCE_REMARK: remark,
            PERFORMANCE_LEADER_ID: admin._id,
            PERFORMANCE_LEADER_NAME: admin.ADMIN_NAME
        };
        
        await PerformanceModel.edit(id, data);
    }

    /**
     * 获取绩效列表
     */
    async getPerformanceList({
        search, // 搜索条件
        sortType, // 搜索菜单
        sortVal, // 搜索菜单
        orderBy, // 排序
        whereEx, // 附加查询条件
        page,
        size,
        isTotal = true,
        oldTotal = 0
    }) {
        orderBy = orderBy || {
            PERFORMANCE_ADD_TIME: 'desc'
        };
        
        let fields = '*';
        
        let where = {};
        where.and = {
            _pid: this.getProjectId() //复杂的查询在此处标注PID
        };
        
        if (util.isDefined(search) && search) {
            where.or = [{
                PERFORMANCE_MEMBER_NAME: ['like', search]
            }, {
                PERFORMANCE_MEMBER_CATE_NAME: ['like', search]
            }, {
                PERFORMANCE_REMARK: ['like', search]
            }];
        } else if (sortType && util.isDefined(sortVal)) {
            // 搜索菜单
            switch (sortType) {
                case 'date': {
                    if (sortVal) {
                        let start = timeUtil.time2Timestamp(sortVal);
                        let end = start + 86400 * 1000 - 1;
                        where.and.PERFORMANCE_START_DATE = ['between', start, end];
                    }
                    break;
                }
                case 'cate': {
                    if (sortVal) where.and.PERFORMANCE_MEMBER_CATE_ID = String(sortVal);
                    break;
                }
                case 'sort': {
                    orderBy = this.fmtOrderBySort(sortVal, 'PERFORMANCE_ADD_TIME');
                    break;
                }
            }
        }
        
        return await PerformanceModel.getList(where, fields, orderBy, page, size, isTotal, oldTotal);
    }

    /**
     * 获取导出数据URL
     */
    async getPerformanceDataURL() {
        return await exportUtil.getExportDataURL(EXPORT_PERFORMANCE_DATA_KEY);
    }

    /**
     * 导出绩效数据Excel
     */
    async exportPerformanceDataExcel(condition, startDate, endDate) {
        let where = {};
        
        if (condition) {
            where = JSON.parse(decodeURIComponent(condition));
        }
        
        // 如果有日期条件，添加到查询中
        if (startDate && endDate) {
            where.and = where.and || {};
            where.and.PERFORMANCE_START_DATE = ['>=', startDate];
            where.and.PERFORMANCE_END_DATE = ['<=', endDate];
        }
        
        // 计算总数
        let total = await PerformanceModel.count(where);
        console.log('[ExportPerformance] TOTAL=' + total);
        
        // 定义存储数据
        let data = [];
        
        const options = {
            '!cols': [
                { column: '序号', wch: 10 },
                { column: '工作人员', wch: 15 },
                { column: '岗位类型', wch: 15 },
                { column: '工单数量', wch: 10 },
                { column: '工分', wch: 10 },
                { column: '绩效奖金(元)', wch: 15 },
                { column: '评分', wch: 10 },
                { column: '执行评价', wch: 30 },
                { column: '统计开始时间', wch: 18 },
                { column: '统计结束时间', wch: 18 },
                { column: '评价人', wch: 15 }
            ]
        };
        
        // 标题栏
        let ROW_TITLE = options['!cols'].map((item) => (item.column));
        data.push(ROW_TITLE);
        
        // 按每次100条导出数据
        let size = 100;
        let page = Math.ceil(total / size);
        let orderBy = {
            'PERFORMANCE_ADD_TIME': 'desc'
        };
        
        let order = 0;
        for (let i = 1; i <= page; i++) {
            let list = await PerformanceModel.getList(where, '*', orderBy, i, size, false);
            console.log('[ExportPerformance] Now export cnt=' + list.list.length);
            
            for (let k = 0; k < list.list.length; k++) {
                let node = list.list[k];
                
                order++;
                
                // 数据节点
                let arr = [];
                arr.push(order);
                arr.push(node.PERFORMANCE_MEMBER_NAME);
                arr.push(node.PERFORMANCE_MEMBER_CATE_NAME);
                arr.push(node.PERFORMANCE_TASK_CNT);
                arr.push(node.PERFORMANCE_WORK_POINTS);
                arr.push(node.PERFORMANCE_BONUS);
                arr.push(node.PERFORMANCE_SCORE);
                arr.push(node.PERFORMANCE_REMARK);
                arr.push(timeUtil.timestamp2Time(node.PERFORMANCE_START_DATE, 'Y-M-D'));
                arr.push(timeUtil.timestamp2Time(node.PERFORMANCE_END_DATE, 'Y-M-D'));
                arr.push(node.PERFORMANCE_LEADER_NAME);
                
                data.push(arr);
            }
        }
        
        return await exportUtil.exportDataExcel(EXPORT_PERFORMANCE_DATA_KEY, '绩效统计数据', total, data, options);
    }

    /**
     * 删除导出数据
     */
    async deletePerformanceDataExcel() {
        return await exportUtil.deleteDataExcel(EXPORT_PERFORMANCE_DATA_KEY);
    }
}

module.exports = AdminPerformanceService; 